<script setup>
import { computed } from 'vue'
// 定义组件属性
const props = defineProps({
  // 对齐方式
  align: {
    type: String,
    default: 'left'
  },
  // 标签是否可见
  labelVisible: {
    type: Boolean,
    default: true
  },
  // 是否必填
  required: {
    type: Boolean,
    default: false
  },
  // 标签文本
  label: {
    type: String,
    default: ''
  },
  // 标签宽度
  labelWidth: {
    type: String,
    default: ''
  },
  // 占位符
  placeholder: {
    type: String,
    default: ''
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  // 是否只读
  readonly: {
    type: Boolean,
    default: false
  },
  // 行数
  rows: {
    type: Number,
    default: 4
  },
  // 最大长度限制
  maxLength: {
    type: Number,
    default: 0 // 0表示无限制
  }
})

// 双向绑定值
const value = defineModel()

// 计算当前输入长度
const currentLength = computed(() => {
  return value.value ? value.value.length : 0
})
</script>

<template>
  <div :class="['flex', align === 'top' ? 'flex-col items-stretch' : 'items-start']">
    <!-- 标签部分 -->
    <div v-if="labelVisible" class="text-sm flex items-center mr-1 font-medium">
      <template v-if="$slots.label">
        <span v-if="required" class="text-red-500 mr-0.5">*</span>
        <slot name="label"></slot>
      </template>
      <div v-else :style="{ width: labelWidth, textAlign: align === 'top' ? 'left' : align }">
        <span v-if="required" class="text-red-500 mr-0.5">*</span>
        <span> {{ label }}</span>
      </div>
    </div>

    <!-- 文本区域 -->
    <div class="flex flex-col w-full" :class="align !== 'top' ? 'ml-2' : 'mt-1.5'">
      <textarea :name="label" v-model="value" :rows="rows" :class="['grow rounded-[2px] border-none p-[12px] text-sm bg-[#f7f8fa] font-medium resize-y', {
        'resize-none': rows === 0
      }]" :placeholder="placeholder || '请输入' + props.label" :disabled="disabled" :readonly="readonly"
        :maxlength="maxLength > 0 ? maxLength : undefined" />

      <!-- 长度提示 -->
      <div v-if="maxLength > 0" class="text-xs text-gray-500 mt-1 self-end">
        {{ currentLength }}/{{ maxLength }}
      </div>
    </div>
  </div>
</template>

<style scoped>
textarea::placeholder {
  color: #757575
}

textarea:focus {
  outline: none;
}

textarea:focus-visible {
  outline: none;
}

textarea[disabled] {
  color: #757575;
  resize: none;
}

textarea {
  min-height: 60px;
  line-height: 1.5;
}
</style>